﻿using Dyao.Book.Contract;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace Dyao.Book.Web
{
    /// <summary>
    /// 创建任务中心任务 ModelBinder
    /// </summary>
    public class TaskCenterCreateInputModelBinder : IModelBinder
    {
        public async Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType == typeof(TaskCenterCreateInputDto))
            {
                using (var reader = new StreamReader(bindingContext.HttpContext.Request.Body))
                {
                    var body = await reader.ReadToEndAsync();

                    if (body != null)
                    {
                        var model = Newtonsoft.Json.JsonConvert.DeserializeObject<TaskCenterCreateInputDto>(body);

                        if (model != null)
                        {
                            if (model.ExtraParameters != null && model.ExtraParameters.Count > 0)
                            {
                                model.ParametersString = Newtonsoft.Json.JsonConvert.SerializeObject(model.ExtraParameters, Newtonsoft.Json.Formatting.None);
                            }

                            bindingContext.Result = ModelBindingResult.Success(model);
                        }
                    }
                }
            }
        }
    }
}
